//
//  TKIMImageSelectView.m
//  TKPhotoSelectDemo
//
//  Created by liupm on 16/4/21.
//  Copyright © 2016年 liupm. All rights reserved.
//

#import "TKIMImageSelectView.h"
#import "TKIMImageSelectCell.h"
#import "TKIMImageFooterView.h"
//纵向间距
#define vSpace 5.0
//横向间距
#define hSpace 5.0
//每排个数
#define hCout 4
@interface TKIMImageSelectView()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,TKIMImageSelectCellDelegate,UIGestureRecognizerDelegate>
@property(nonatomic,strong) UICollectionView *collectionView;
//数据源<TKIMPhotoModel>
@property(nonatomic,strong) NSMutableArray *dataSource;
//选中的图片数组
@property(nonatomic,strong) NSMutableArray *selectedSource;
//上一个滑动过的cell
@property(nonatomic,strong) TKIMImageSelectCell *lastCell;
//底部视图
@property(nonatomic,strong) TKIMImageFooterView *footerView;

@end

@implementation TKIMImageSelectView
static NSString * const reuseIdentifier = @"Cell";

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _dataSource = [NSMutableArray array];
        _selectedSource = [NSMutableArray array];
        [self drawView];
    }
    return self;
}


/**
 *  @Author lpm, 16-04-21 10:04:18
 *
 *  @brief  方法
 */
-(void)drawView
{
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.collectionView];
    if ([TKIMImagePickerSet shareInstance].allowsMultipleSelection)
    {
        [self addSubview:self.footerView];
    }
}

/**
 *  @Author lpm, 16-04-21 10:04:43
 *
 *  @brief  刷新数据
 *
 *  @param dataSource
 */
-(void)reloadData:(NSMutableArray *)dataSource
{
    if (dataSource)
    {
        _dataSource = dataSource;
        [self.collectionView reloadData];
        if (dataSource.count)
        {
            //滚动到最底部
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_dataSource.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
        }
        [self.footerView setCount:self.selectedSource.count];
    }
}

-(void)reloadView
{
    [self.collectionView reloadData];
    [self.footerView setCount:self.selectedSource.count];
}

#pragma mark <UICollectionViewDataSource>
/**
 *  @Author lpm, 16-04-20 19:04:00
 *
 *  @brief
 *
 *  @param collectionView
 *
 *  @return
 */
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


/**
 *  @Author lpm, 16-04-20 19:04:09
 *
 *  @brief
 *
 *  @param collectionView
 *  @param section
 *
 *  @return
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSource.count;
}


/**
 *  @Author lpm, 16-04-20 19:04:23
 *
 *  @brief
 *
 *  @param collectionView
 *  @param indexPath
 *
 *  @return
 */
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    TKIMImageSelectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    cell.backgroundColor = [UIColor lightGrayColor];
    TKIMPhotoModel *model = _dataSource[indexPath.row];
    cell.model = model;
    return cell;
}



/**
 *  @Author lpm, 16-04-21 09:04:42
 *
 *  @brief  行被选中
 *
 *  @param collectionView
 *  @param indexPath
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (![TKIMImagePickerSet shareInstance].allowsMultipleSelection)
    {
        TKIMImageSelectCell *cell = (TKIMImageSelectCell *)[collectionView cellForItemAtIndexPath:indexPath];
        [cell doCheck];
        [self routerEventWithName:TKIMImagePreviewEvent userInfo:_selectedSource];
    }
}

#pragma mark 手势相关

/**
 *  @Author lpm, 16-04-21 09:04:32
 *
 *  @brief  长按手势
 *
 *  @param recognizer
 */
- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateChanged && [self.dataSource count] > 0) {
        CGPoint location = [recognizer locationInView:self.collectionView];
        NSIndexPath * indexPath = [self.collectionView indexPathForItemAtPoint:location];
        //如果得出是第一个item需要判断坐标是否是在第一个，indexPathForItemAtPoint存在不准的情况
        if (indexPath.row == 0)
        {
            CGFloat width = (self.frame.size.width- hSpace*(hCout-1))/hCout;
            if (location.y>width || location.x > width)
            {
                return;
            }
        }
        TKIMPhotoModel *object = [self.dataSource objectAtIndex:indexPath.row];
        //如果是视频类型则不做处理
        if (object.isVideoType)
        {
            return;
        }
        
        TKIMImageSelectCell *cell = (TKIMImageSelectCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        //如果手指还在当前的cell上面则不做处理
        if (_lastCell && cell == _lastCell)
        {
            return;
        }
        _lastCell = cell;

        //如果选中数组不包含这张图
        if (![_selectedSource containsObject:object])
        {
            //如果超过了限制
            if (_selectedSource.count == [TKIMImagePickerSet shareInstance].maxAllowSelect)
            {
                return;
            }
            object.isSelected = YES;
            cell.checkBox.selected = YES;
            [_selectedSource addObject:object];
        }
        else
        {
            object.isSelected = NO;
            cell.checkBox.selected = NO;
            [_selectedSource removeObject:object];
        }
        [self.footerView setCount:_selectedSource.count];
    }
}


/**
 *  @Author lpm, 16-04-21 13:04:24
 *
 *  @brief  事件路由
 *
 *  @param eventName
 *  @param userInfo
 */
-(void)routerEventWithName:(NSString *)eventName userInfo:(NSObject *)userInfo
{
    if([eventName isEqualToString:TKIMImagePreviewEvent])
    {
        [super routerEventWithName:TKIMImagePreviewEvent userInfo:_selectedSource];
    }
    else if([eventName isEqualToString:TKIMImageConfirmEvent])
    {
        [super routerEventWithName:TKIMImageConfirmEvent userInfo:_selectedSource];
    }
    else
    {
        [super routerEventWithName:eventName userInfo:userInfo];
    }
}

#pragma mark cell代理

/**
 *  @Author lpm, 16-04-21 10:04:29
 *
 *  @brief  媒体文件被选中
 *
 *  @param model
 *  @param isSelected
 */
-(void)photo:(TKIMPhotoModel *)model isSelected:(BOOL)isSelected
{
    if (isSelected)
    {
        if (_selectedSource.count == [TKIMImagePickerSet shareInstance].maxAllowSelect)
        {
            if ([TKIMImagePickerSet shareInstance].allowsMultipleSelection)
            {
                NSString *title = [NSString stringWithFormat:@"最多只允许选择%d张图",[TKIMImagePickerSet shareInstance].maxAllowSelect];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:nil delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                [alert show];
            }
            model.isSelected = NO;
            NSInteger index = [self.dataSource indexOfObject:model];
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
            TKIMImageSelectCell *cell = (TKIMImageSelectCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            cell.checkBox.selected = NO;
            return;
        }
        [_selectedSource addObject:model];
    }
    else
    {
        [_selectedSource removeObject:model];
    }
    [self.footerView setCount:_selectedSource.count];
}

#pragma mark 属性

-(UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width = (self.frame.size.width- hSpace*(hCout-1))/hCout;
        layout.itemSize =  CGSizeMake(width,width);
        layout.minimumLineSpacing = vSpace;
        layout.minimumInteritemSpacing = hSpace;
        CGFloat height = self.frame.size.height-self.footerView.frame.size.height-10;
        if (![TKIMImagePickerSet shareInstance].allowsMultipleSelection)
        {
            height = self.frame.size.height;
        }
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 5, self.frame.size.width, height) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate =self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[TKIMImageSelectCell class] forCellWithReuseIdentifier:reuseIdentifier];
        _collectionView.allowsMultipleSelection = YES;
        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        lpgr.minimumPressDuration = 0.3;
        lpgr.delegate = self;
        [_collectionView addGestureRecognizer:lpgr];
        _collectionView.userInteractionEnabled = YES;
    }
    return _collectionView;
}


-(UIView *)footerView
{
    if (!_footerView)
    {
        _footerView = [[TKIMImageFooterView alloc] initWithFrame:CGRectMake(0, self.frame.size.height-44, self.frame.size.width, 44)];
        _footerView.backgroundColor = self.backgroundColor;
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _footerView.frame.size.width, 0.5)];
        line.backgroundColor = [UIColor lightGrayColor];
        [_footerView addSubview:line];
    }
    return _footerView;
}

@end
